//
//  MusicPlayViewController.m
//  XMLY
//
//  Created by lanou on 15/11/6.
//  Copyright © 2015年 曾杰. All rights reserved.
//

#import "MusicPlayViewController.h"
#import "PlayView.h"
#import "PKPlayerManger.h"
#import "PKRequestManager.h"
#import "ChildListModel.h"
#import <MediaPlayer/MediaPlayer.h>
#import "UIImageView+WebCache.h"
@interface MusicPlayViewController ()
@property (nonatomic, strong)PlayView * playView;
@property (nonatomic, strong)NSMutableArray * musicUrlArr;
@property (nonatomic, strong)PKPlayerManger * player;
@property (nonatomic, strong)NSTimer * timer;
@property (nonatomic, strong)NSMutableArray * musicOtherArr;
@property (nonatomic, strong)NSTimer * timer1;
@property (nonatomic, assign) CGAffineTransform transform;
@end

@implementation MusicPlayViewController

-(NSMutableArray *)musicOtherArr
{
    if (_musicOtherArr == nil) {
        self.musicOtherArr = [NSMutableArray array];
    }
    return _musicOtherArr;
}


-(NSMutableArray *)musicUrlArr
{
    if (_musicUrlArr==nil) {
        self.musicUrlArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _musicUrlArr;
}

-(void)requestData
{

     NSString * url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/%@?device=android",self.trackId];
     [PKRequestManager requestWithType:GET urlString:url parDic:nil finish:^(NSData *data) {
        
             
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
          ChildListModel * model = [[ChildListModel alloc]init];
          [model setValuesForKeysWithDictionary:dic];
          [self.musicOtherArr addObject:model];
        
          [self.musicUrlArr addObject:model.playUrl64];
          [self.playView configureViewWithModel:model];
           NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
          NSString *playTitle = [defaults valueForKey:@"playTitle"];
          //播放的标题相同则继续播放
          if ([model.title isEqualToString:playTitle]) {
              
          }else
          {
              self.index=0;
              [_player setMangerMusicArray:self.musicUrlArr];
              [_player playWithIndex:self.index];
              _player.musicArr=self.musicOtherArr;
              _player.index = self.index;
               [self configNowPlayingInfoCenter];
          }
          
          //通知rootleftcontroller下方的播放视图
          [self notificationRootLeftController:model];
        
      
         
     } error:^(NSError *error) {
         NSLog(@"%@",error);
     }];
      

    
}


-(void)viewWillDisappear:(BOOL)animated
{
    
    [_timer invalidate];
    [_timer1 invalidate];
    NSLog(@"**************");
    _timer = nil;
    _timer1 = nil;
 [[NSNotificationCenter defaultCenter]postNotificationName:@"changeButtonImage" object:nil userInfo:nil];
    
}




-(void)viewWillAppear:(BOOL)animated
{

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeButtonIamge) name:@"changeButtonImage" object:nil];
    _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
    _timer1 = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(changeContentOffSet) userInfo:nil repeats:YES];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _playView = [[PlayView alloc]initWithFrame:self.view.bounds];
    
    [self.view addSubview:_playView];
    _playView.pictureView.image = [UIImage imageNamed:@"playList"];
     _player = [PKPlayerManger shareManger];
    _player.musicPlayVC = self;
   
    if (self.musicArr.count==0) {
       
      
            [self requestData];
          }
    else
    {
    
       for (int i = 0; i<self.musicArr.count; i++) {
        NSString * playUrl = ((ChildListModel *)self.musicArr[i]).playUrl64;
        [self.musicUrlArr addObject:playUrl];
    }
        _player.musicArr=self.musicArr;
        _player.index = self.index;
       
        [_playView configureViewWithModel:self.musicArr[self.index]];

        ChildListModel *model = self.musicArr[self.index];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *playTitle = [defaults valueForKey:@"playTitle"];
        //播放的标题相同则继续播放
        if ([model.title isEqualToString:playTitle]) {
            
        }else
        {
            [_player setMangerMusicArray:self.musicUrlArr];
            [_player playWithIndex:self.index];
              [self configNowPlayingInfoCenter];
           
        }
        //通知rootleftcontroller下方的播放视图
        [self notificationRootLeftController:model];
    }

    [_playView.backBtn addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];

    [_playView.beforeBtn addTarget:self action:@selector(didClickBeforeBtn) forControlEvents:(UIControlEventTouchUpInside)];
    [_playView.playAndPause addTarget:self action:@selector(didClickPlayAndPauseBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [_playView.nextBtn addTarget:self action:@selector(didClickNextBtn) forControlEvents:(UIControlEventTouchUpInside)];
    [_playView.slider addTarget:self action:@selector(sliderBeginSlide:) forControlEvents:(UIControlEventValueChanged)];
   
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(configureView) name:@"indexChange" object:nil];
   
}

-(void)configureView
{

    self.index = _player.index;
    if (self.musicArr.count !=0) {
        [_playView configureViewWithModel:self.musicArr[self.index]];
        
    }
    else
    {
        [_playView configureViewWithModel:self.musicOtherArr[self.index]];
    }
    
}


-(void)changeContentOffSet
{
    
    CGPoint pt = [_playView.scrollLabel contentOffset];
    CGFloat n = pt.x + 1;
    _playView.scrollLabel.contentOffset = CGPointMake(n, pt.y);
    if (_playView.scrollLabel.contentOffset.x>_playView.scrollLabel.frame.size.width) {
       _playView.scrollLabel.contentOffset = CGPointMake(-pt.x, pt.y);
    }
    
}




-(void)didClickNextBtn
{

    self.index++;
    if (self.index==self.musicUrlArr.count) {
        self.index=0;
    }
    if (self.musicArr.count !=0) {
            [_playView configureViewWithModel:self.musicArr[self.index]];

    }
    else
    {
            [_playView configureViewWithModel:self.musicOtherArr[self.index]];
    }
    [_player playWithIndex:self.index];
    [self changeButtonIamge];
    //通知rootleftcontroller下方的播放视图
    ChildListModel *model = self.musicArr[self.index];
    [self notificationRootLeftController:model];
    [self configNowPlayingInfoCenter];
}


-(void)configNowPlayingInfoCenter{
    
    _player.index = self.index;
    
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        ChildListModel * model = [_player.musicArr objectAtIndex:_player.index];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        //歌曲名称
        [dict setObject:model.title forKey:MPMediaItemPropertyTitle];
        
        //演唱者
        //        [dict setObject:[info objectForKey:@"singer"] forKey:MPMediaItemPropertyArtist];
        //
        //        //专辑名
        //        [dict setObject:[info objectForKey:@"album"] forKey:MPMediaItemPropertyAlbumTitle];
        //
        //        //专辑缩略图
        UIImage *image =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.coverLarge]]];
        if (image !=nil) {
            
            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
            [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
            //
        }
        //音乐剩余时长
        [dict setObject:[NSNumber numberWithDouble:self.player.finishTime-self.player.currentTime] forKey:MPMediaItemPropertyPlaybackDuration];
        
        //音乐当前播放时间 在计时器中修改
        [dict setObject:[NSNumber numberWithDouble:self.player.currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
        
        //设置锁屏状态下屏幕显示播放音乐信息
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    }
}


-(void)sliderBeginSlide:(UISlider *)slider
{
    [_player seekToTime:slider.value];
    [self changeButtonIamge];
}

-(void)changeButtonIamge
{
    
    if (_player.avPlayer.rate==1.0) {
        [_playView.playAndPause setImage:[UIImage imageNamed:@"zanting"] forState:(UIControlStateNormal)];
    }
    else
    {
        [_playView.playAndPause setImage:[UIImage imageNamed:@"bofang"] forState:(UIControlStateNormal)];
    }
}






-(void)didClickPlayAndPauseBtn:(UIButton *)button
{

    [_player playAndPause];
   
    [self changeButtonIamge];
    [self configNowPlayingInfoCenter];
}

-(void)didClickBeforeBtn
{
   self.index--;
    if (self.index==-1) {
        self.index = self.musicUrlArr.count-1;
    }
    if (self.musicArr.count !=0) {
        [_playView configureViewWithModel:self.musicArr[self.index]];
        
    }
    else
    {
        [_playView configureViewWithModel:self.musicOtherArr[self.index]];
    }
       [_player playWithIndex:self.index];
    [self changeButtonIamge];
    
    //通知rootleftcontroller下方的播放视图
    ChildListModel *model = self.musicArr[self.index];
    [self notificationRootLeftController:model];
    [self configNowPlayingInfoCenter];
}

-(void)back
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    ChildListModel *model = self.musicArr[self.index];
    [defaults setObject:model.title forKey:@"playTitle"];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)timeChange{
    [self imageViewRorate];
       
    _playView.slider.minimumValue = 0.0;
    _playView.slider.maximumValue = _player.finishTime;
    _player.musicTitle = _playView.scrollLabel.text;
    NSUInteger yuTime = _player.finishTime - _player.currentTime;
    NSString *minutes = [NSString stringWithFormat:@"%02lu", yuTime / 60];
    NSString *seconds = [NSString stringWithFormat:@"%02lu", yuTime % 60];
    _playView.timeLabel.text = [[minutes stringByAppendingString:@":"] stringByAppendingString:seconds];
        _playView.slider.value = _player.currentTime;
    if (_player.currentTime==_player.finishTime-2) {
        [self didClickNextBtn];
        
    }
   
}


//通知rootleftcontroller下方的播放视图
- (void)notificationRootLeftController:(ChildListModel *)model
{
    //通知rootleftcontroller
    NSNotificationCenter *notifi = [NSNotificationCenter defaultCenter];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"pic"] = model.albumImage;
    NSLog(@"%@",model.albumImage);
    dic[@"title"] = model.title;
    [notifi postNotificationName:@"play" object:@"p" userInfo:dic];
}

#warning 旋转
- (void)imageViewRorate{
    _transform = _playView.mainImageView.transform;
    if (_player.avPlayer.rate == 1.0) {
        
        [UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            //            _playView.mainImageView.transform = _transform;
            _playView.mainImageView.transform = CGAffineTransformRotate(_transform, M_PI_4 / 10.0);
        } completion:^(BOOL finished) {
            //            [self imageViewRorate];
        }];
    }else{
        _playView.mainImageView.transform = _transform;
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
